<template>
  <div class="app-container" v-loading="pageLoading" element-loading-text="加载中..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(255,255,255,0.8)">
    <template v-if="!pageLoading">
    <div class="detail-header">
      <div class="left">
        <span class="title">维修单</span>
      </div>
      <div class="right">
        <el-button v-if="!isReadonly" size="small" type="primary" @click="saveWork">完成维修</el-button>
        <el-button size="small" type="primary" plain @click="openHistory">状态履历</el-button>
      </div>
    </div>


    <el-tabs v-model="active">
      <el-tab-pane label="维修信息" name="repair">
        <template v-if="isReadonly">
          <el-descriptions :column="descriptionsCols" border>
            <el-descriptions-item label="维修单号">{{ work.workNo || '-' }}</el-descriptions-item>
            <el-descriptions-item label="报修单号">{{ order.reportNo || work.reportNo || work.rptNo || '-' }}</el-descriptions-item>
            <el-descriptions-item label="故障原因" :span="3">{{ work.faultCause || '-' }}</el-descriptions-item>
            <el-descriptions-item label="故障对策" :span="3">{{ work.countermeasure || '-' }}</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ work.startTime || '-' }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ work.endTime || '-' }}</el-descriptions-item>
            <el-descriptions-item label="维修人员">{{ assigneeName || '-' }}</el-descriptions-item>
          </el-descriptions>
        </template>
        <template v-else>
          <el-form :model="work" :rules="workRules" ref="workForm" label-width="90px">
            <el-row :gutter="20">
              <el-col :lg="8" :md="12" :sm="24">
                <el-form-item label="维修单号">{{ work.workNo }}</el-form-item>
              </el-col>
              <el-col :lg="8" :md="12" :sm="24">
                <el-form-item label="报修单号">{{ order.reportNo || work.reportNo || work.rptNo }}</el-form-item>
              </el-col>

              <el-col :lg="24" :md="24" :sm="24">
                <el-form-item label="故障原因" prop="faultCause">
                  <el-input v-model="work.faultCause" placeholder="请输入故障原因" />
                </el-form-item>
              </el-col>
              <el-col :lg="24" :md="24" :sm="24">
                <el-form-item label="故障对策" prop="countermeasure">
                  <el-input v-model="work.countermeasure" placeholder="请输入故障对策" />
                </el-form-item>
              </el-col>
              <el-col :lg="8" :md="12" :sm="24">
                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker v-model="work.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" style="width:100%" />
                </el-form-item>
              </el-col>
              <el-col :lg="8" :md="12" :sm="24">
                <el-form-item label="结束时间" prop="endTime">
                  <el-date-picker v-model="work.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" style="width:100%" />
                </el-form-item>
              </el-col>
              <el-col :lg="8" :md="12" :sm="24">
                <el-form-item label="维修人员">{{ assigneeName || '-' }}</el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>

        <!-- 备件信息（显示在维修信息下半部分） -->
        <el-card shadow="never" class="mt12" header="备件信息">
          <el-table :data="parts" border class="responsive-table" :fit="false">
            <el-table-column label="备件名称" prop="name" :min-width="160" show-overflow-tooltip />
            <el-table-column label="规格型号" prop="model" :min-width="160" show-overflow-tooltip />
            <el-table-column label="备件类型" prop="type" :min-width="140" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ getPartTypeName(scope.row.type) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="理论在库数" prop="stock" :min-width="120" />
            <el-table-column label="申请数量" :min-width="160">
              <template slot-scope="scope">
                <span v-if="isReadonly">{{ scope.row.used || 0 }}</span>
                <el-input-number v-else v-model="scope.row.used" :min="0" :max="Number(scope.row.stock)||0" :step="1" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="出库仓库" :min-width="180" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-if="isReadonly">{{ getWarehouseName(scope.row.selectedWarehouse) || scope.row.warehouseCode || '-' }}</span>
                <el-select v-else v-model="scope.row.selectedWarehouse" placeholder="选择仓库" size="small" style="width: 100%;">
                  <el-option
                    v-for="warehouse in warehouseOptions"
                    :key="warehouse.code || warehouse.value"
                    :label="warehouse.name || warehouse.label"
                    :value="warehouse.code || warehouse.value">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="基本信息" name="basic">
        <el-descriptions :column="descriptionsCols" border>
          <el-descriptions-item label="资产编号">{{ order.assetNo || '-' }}</el-descriptions-item>
          <el-descriptions-item label="类型">{{ order.assetTypeName || typeName(order.assetType) }}</el-descriptions-item>
          <el-descriptions-item label="名称">{{ order.assetName }}</el-descriptions-item>
          <el-descriptions-item label="位置">{{ order.location }}</el-descriptions-item>
          <el-descriptions-item label="使用部门">{{ order.deptName }}</el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>

      <el-tab-pane label="故障信息" name="fault">
        <el-descriptions :column="descriptionsCols" border>
          <el-descriptions-item label="发生时间">{{ order.occurTime }}</el-descriptions-item>
          <el-descriptions-item label="报修人">{{ order.reporter }}</el-descriptions-item>
          <el-descriptions-item label="紧急程度">{{ order.urgencyName }}</el-descriptions-item>
          <el-descriptions-item label="报修类型">{{ order.reportTypeName }}</el-descriptions-item>
          <el-descriptions-item label="报修时间">{{ order.reportTime }}</el-descriptions-item>
          <el-descriptions-item label="故障描述" :span="3">{{ order.faultDescription }}</el-descriptions-item>
        </el-descriptions>
        <el-card shadow="never" class="mt12" header="故障图片">
          <image-upload ref="image" v-model="images" :limit="5" :readonly="true" />
        </el-card>
      </el-tab-pane>


    </el-tabs>

    <el-dialog title="状态履历" :visible.sync="historyVisible" width="600px">
      <div v-if="historyList.length === 0" class="no-history">
        <i class="el-icon-info"></i>
        <p>暂无维修履历记录</p>
      </div>
      <el-timeline v-else>
        <el-timeline-item
          v-for="(h, idx) in historyList"
          :key="idx"
          :timestamp="formatTime(h.time)"
          placement="top"
          :type="getTimelineType(h.operation)"
        >
          <el-card>
            <h4>{{ h.operation }}</h4>
            <p><strong>操作人：</strong>{{ h.operator }}</p>
            <p v-if="h.description"><strong>描述：</strong>{{ h.description }}</p>
            <p v-if="h.result"><strong>结果：</strong>
              <el-tag :type="getResultTagType(h.result)" size="mini">
                {{ getResultName(h.result) }}
              </el-tag>
            </p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <span slot="footer" class="dialog-footer">
        <el-button @click="historyVisible=false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 右下角固定返回按钮 -->
    <el-button class="floating-back" type="default" @click="handleBack">返 回</el-button>
    </template>
  </div>
</template>

<script>
import { getWork } from '@/api/repair/work'
import { getOrder } from '@/api/repair/order'
import ImageUpload from '@/views/components/ImageUpload.vue'
import { updateWork } from '@/api/repair/work'
import { listParts } from '@/api/inventory/part'
import { listWorkPart } from '@/api/inventory/workPart'
import { listWarehouseDTO } from '@/api/inventory/warehouse'
import { listPartType } from '@/api/dict/partType'

export default {
  name: 'WorkDetail',
  components: { ImageUpload },
  data() {
    return {
      active: 'repair',
      work: {},
      order: {},
      images: [],
      parts: [],
      assigneeName: '',
      historyVisible: false,
      historyList: [],
      isReadonly: true,
      defaultWarehouseCode: '',
      warehouseOptions: [],
      selectedWarehouse: '',
      loading: true,
      pageLoading: true,
      descriptionsCols: 3,
      // 添加表单验证规则
      _imageUrlsToInit: [],
      workRules: {
        faultCause: [
          { required: true, message: '请输入故障原因', trigger: 'blur' }
        ],
        countermeasure: [
          { required: true, message: '请输入故障对策', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'blur' },
          { validator: this.validateStartTime, trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'blur' },
          { validator: this.validateEndTime, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    imageUrls() {
      return this.images.map(img => img.url).filter(Boolean)
    }
  },
  async created() {
    const { workNo } = this.$route.params
    this.loading = true
    try {
      // 1) 并行预取固定字典
      await Promise.all([this.getWarehouseOptions(), this.loadPartTypes()])
      // 2) 获取工单详情
      const workRes = await getWork(workNo)
      const w = workRes.data || {}
      this.work = w
      this.assigneeName = w.assigneeName || ''
      if (!this.assigneeName && w.assigneeId) {
        await this.getUserById(w.assigneeId)
      }
      // 3) 若有关联报修，先获取报修详情
      const rpt = w.reportNo || w.rptNo
      let urls = []
      let assetNo = ''
      if (rpt) {
        const orderRes = await getOrder(rpt)
        const order = orderRes.data || {}
        assetNo = order.assetNo || ''
        const raw = order.imageUrls || order.images || order.image_urls
        if (Array.isArray(raw)) urls = raw
        else if (typeof raw === 'string' && raw.trim()) {
          const s = raw.trim()
          if (s.startsWith('[')) { try { urls = JSON.parse(s) || [] } catch(e) { urls = [] } }
          else if (s.includes(',')) { urls = s.split(',').map(x=>x.trim()).filter(Boolean) }
          else { urls = [s] }
        }
        this.order = order
      }
      // 4) 图片与配件并行准备（若有资产号）
      if (assetNo) {
        const [partsRes, workPartRes] = await Promise.all([
          listParts({ pageNum: 1, pageSize: 9999, assetNo }),
          listWorkPart({ workNo })
        ])
        let rows = partsRes.rows || []
        rows = rows.filter(p => {
          const json = p.associatedAssetsJson || p.associatedAssets || p.assetNos || ''
          try {
            if (!json) return false
            const arr = Array.isArray(json) ? json : JSON.parse(json)
            return (arr || []).some(a => String(a.assetNo || a) === String(assetNo))
          } catch(e) {
            return String(json).split(',').map(s=>s.trim()).includes(String(assetNo))
          }
        })
        const workParts = workPartRes.rows || workPartRes.data || []
        const workPartMap = {}
        const workPartStockMap = {}
        workParts.forEach(wp => {
          if (wp.partNo && wp.quantity > 0) {
            workPartMap[wp.partNo] = wp.quantity
            workPartStockMap[wp.partNo] = wp.stockAtTime || wp.stock || 0
          }
        })
        this.parts = rows.map(p => {
          const partNo = p.partNo || p.code || p.sn || ''
          return {
            partNo,
            name: p.partName || p.name || '',
            model: p.specNo || p.model || p.specModel || '',
            type: p.partTypeName || p.partTypeCode || p.type || '',
            stock: workPartStockMap[partNo] || p.stock || p.stockTotal || p.totalStock || p.qty || 0,
            used: workPartMap[partNo] || 0,
            warehouseId: p.warehouseId || 1,
            warehouseCode: p.warehouseCode || p.warehouse || p.whCode || '',
            selectedWarehouse: p.warehouseCode || p.warehouse || p.whCode || this.selectedWarehouse || ''
          }
        })
      }
      // 5) 处理图片并延迟到渲染后初始化
      this.images = (urls || []).map(u => ({ name: String(u).split('/').pop(), url: this.toPreviewUrl(u), rawName: u }))
      // 读取只读参数
      this.isReadonly = String((this.$route.query && this.$route.query.readonly) || '1') !== '0'
      await this.$nextTick()
      if (this.$refs.image && this.$refs.image.initFromUrls) {
        this.$refs.image.initFromUrls((urls || []).map(u => this.toPreviewUrl(u)))
      }
      this.pageLoading = false
    } catch (error) {
      console.error('加载工单详情失败:', error)
      this.$message.error('加载数据失败，请重试')
    } finally {
      this.loading = false
      // 根据窗口宽度自适应描述列数
      this.updateDescriptionCols()
    }
  },
  methods: {
    updateDescriptionCols() {
      const width = window.innerWidth || document.documentElement.clientWidth
      if (width >= 1600) {
        this.descriptionsCols = 4
      } else if (width >= 1200) {
        this.descriptionsCols = 3
      } else if (width >= 768) {
        this.descriptionsCols = 2
      } else {
        this.descriptionsCols = 1
      }
    },
    async loadPartTypes() {
      try {
        const res = await listPartType({ pageNum: 1, pageSize: 9999, enabled: 1 })
        const partTypes = res.rows || res.data || []
        // 将备件类型数据存储到全局，供TypeTag组件使用
        this.$partTypeLoaded = true
        this.$partTypeOptions = partTypes
        return partTypes
      } catch (error) {
        console.error('加载备件类型失败:', error)
        this.$partTypeLoaded = true
        this.$partTypeOptions = []
        return []
      }
    },
    validateStartTime(rule, value, callback) {
      // 如果值为空，不显示错误（让required规则处理）
      if (!value) {
        callback();
        return;
      }

      const selectedDate = new Date(value);
      const today = new Date();
      today.setHours(0, 0, 0, 0); // 将今天的时间部分设置为0，只比较日期部分

      if (selectedDate + 1 > today) {
        callback(new Error('开始时间不能是今天之后的日期'));
        return;
      }

      callback();
    },
    validateEndTime(rule, value, callback) {
      // 如果值为空，不显示错误（让required规则处理）
      if (!value) {
        callback();
        return;
      }

      const endDate = new Date(value);
      const startDate = new Date(this.work.startTime);

      // 只有当开始时间已选择时才进行比较
      if (this.work.startTime && endDate < startDate) {
        callback(new Error('结束时间不能早于开始时间'));
        return;
      }

      callback();
    },
    async getWarehouseOptions() {
      try {
        const res = await listWarehouseDTO({ pageNum: 1, pageSize: 9999 })
        const warehouses = res.data || []
        this.warehouseOptions = warehouses.map(w => ({
          name: w.name || w.warehouseName || w.code,
          label: w.name || w.warehouseName || w.code,
          code: w.code || w.warehouseCode,
          value: w.code || w.warehouseCode
        }))
        // 设置默认选中第一个仓库
        if (this.warehouseOptions.length > 0 && !this.selectedWarehouse) {
          this.selectedWarehouse = this.warehouseOptions[0].code || this.warehouseOptions[0].value
        }
      } catch (err) {
        // 如果获取失败，使用默认选项
        this.warehouseOptions = [
          { name: '默认仓库', label: '默认仓库', code: 'DEFAULT', value: 'DEFAULT' }
        ]
        this.selectedWarehouse = 'DEFAULT'
      }
    },
    getWarehouseName(warehouseCode) {
      if (!warehouseCode) return ''
      const warehouse = this.warehouseOptions.find(w => (w.code || w.value) === warehouseCode)
      return warehouse ? (warehouse.name || warehouse.label) : warehouseCode
    },
    makeAbsUrl(u) {
      if (!u) return ''
      if (/^https?:\/\//i.test(u)) return u
      const base = (process.env && process.env.VUE_APP_BASE_API) || ''
      if (u.startsWith('/')) return base + u
      return base + '/' + u
    },
    toPreviewUrl(path) {
      if (!path) return ''
      let s = String(path)
      if (/^https?:\/\//i.test(s)) return s

      // MinIO 图片显示地址配置
      const minioBaseUrl = 'https://io.brightholdings.cn/smart-maintenance/'

      // 如果是MinIO存储的图片，直接拼接MinIO地址
      if (s && !s.startsWith('http')) {
        // 移除可能存在的本地路径前缀
        let cleanPath = s
        if (s.startsWith('/profile/upload/')) {
          cleanPath = s.substring('/profile/upload/'.length)
        } else if (s.startsWith('profile/upload/')) {
          cleanPath = s.substring('profile/upload/'.length)
        }
        return minioBaseUrl + cleanPath
      }

      return s
    },
    // 将备件类型编码映射为名称（使用已预加载的字典）
    getPartTypeName(code) {
      if (!code) return '-'
      const list = this.$partTypeOptions || []
      const item = list.find(it => String(it.code) === String(code) || String(it.value) === String(code) || String(it.partTypeCode) === String(code))
      return item ? (item.name || item.label) : code
    },
    loadWarehouses() {
      // 动态引入，避免循环依赖
      import('@/api/inventory/warehouse').then(mod => {
        if (mod && mod.listWarehouse) {
          mod.listWarehouse({ pageNum: 1, pageSize: 9999 }).then(res => {
            this.warehouseOptions = res.rows || res.data || []
          }).catch(() => {})
        }
      }).catch(() => {})
    },
    saveWork() {
      // 表单验证
      this.$refs.workForm.validate((valid) => {
        if (!valid) {
          this.$message.error('请填写必填项');
          return;
        }

        // 校验结束时间不能早于开始时间
        if (this.work.startTime && this.work.endTime) {
          const start = new Date(this.work.startTime);
          const end = new Date(this.work.endTime);
          if (end < start) {
            this.$message.error('结束时间不能早于开始时间');
            return;
          }
        }

        // 1) 保存维修信息，同时将状态更新为"待确认"
        const workData = { ...this.work, statusCode: 'PENDING_CONFIRM' }
        updateWork(workData).then(() => {
          // 2) 保存维修用料到 t_work_part 表，同时保存维修时的库存快照
          const workParts = (this.parts || []).filter(p => Number(p.used) > 0)
            .map(p => ({
              workNo: this.work.workNo,
              partNo: p.partNo,
              warehouseId: p.warehouseId || 1, // 默认仓库ID，后续可优化
              quantity: Number(p.used),
              stockAtTime: p.stock || 0, // 保存维修时的库存快照
              isDelete: 0
            }))

          // 3) 汇总申请数量>0的用料，调用出库接口（维修出库）
          const materials = (this.parts || []).filter(p => Number(p.used) > 0)
            .map(p => ({
              partNo: p.partNo,
              partName: p.name,
              specNo: p.model,
              partTypeCode: p.type,
              quantity: Math.floor(p.used),
              warehouseCode: p.selectedWarehouse || p.warehouseCode || p.warehouse || p.whCode || '',
            }))
          if (materials.length === 0) {
            this.$message.success('维修完成')
            // 完成维修后自动返回
            this.handleBack()
            return
          }
          // 检查是否所有备件都选择了仓库
          const missingWarehouse = materials.find(m => !m.warehouseCode)
          if (missingWarehouse) {
            this.$message.error('请为所有备件选择出库仓库')
            return
          }
          // 头部仓库：使用第一个备件的仓库
          const headWarehouseCode = materials[0].warehouseCode

          // 先删除旧的维修用料，再保存新的
          import('@/api/inventory/workPart').then(workPartMod => {
            // 先删除该维修单的所有旧用料记录
            workPartMod.listWorkPart({ workNo: this.work.workNo }).then(oldRes => {
              const oldParts = oldRes.rows || oldRes.data || []
              if (oldParts.length > 0) {
                const deleteIds = oldParts.map(p => p.id).filter(id => id)
                if (deleteIds.length > 0) {
                  return workPartMod.delWorkPart(deleteIds.join(','))
                }
              }
              return Promise.resolve()
            }).then(() => {
              // 再保存新的维修用料
              const savePromises = workParts.map(wp => workPartMod.addWorkPart(wp))
              return Promise.all(savePromises)
            }).then(() => {
              // 再生成出库单
              const payload = {
                txType: 'OUTBOUND',
                warehouseCode: headWarehouseCode,
                bizRefType: 'REPAIR',
                remark: `维修单${this.work.workNo || ''}用料`,
                partList: materials
              }
              return import('@/api/inventory/transaction').then(mod => mod.addTransaction(payload))
            }).then(() => {
              this.$message.success('维修完成，已生成维修出库')
              // 完成维修后自动返回
              this.handleBack()
            }).catch(() => {
              this.$message.error('维修完成，但生成维修出库失败')
              // 即使出库失败，也返回列表
              this.handleBack()
            })
          })
        })
      });
    },
    async getUserById(userId) {
      // 根据用户ID获取用户姓名
      try {
        const request = await import('@/utils/request')
        const res = await request.default({ url: '/system/user/' + userId, method: 'get' })
        const user = res.data || {}
        this.assigneeName = user.nickName || user.userName || user.realName || ''
      } catch (error) {
        // 如果获取失败，保持为空
        console.error('获取用户信息失败:', error)
      }
    },
    handleBack() {
      // 1) 优先回到进入详情前记录的列表fullPath（带筛选/分页状态）
      let saved = ''
      try { saved = sessionStorage.getItem('work-list-return') || '' } catch(e) {}
      // 2) 其次回到已存在的列表标签
      if (!saved) {
        const views = (this.$store && this.$store.state && this.$store.state.tagsView && this.$store.state.tagsView.visitedViews) || []
        // 优先查找"我的维修"页面，其次查找维修管理页面
        const existed = views.find(v => v.name === 'MyWorkList') || views.find(v => v.path === '/repair/work/index') ||
                       views.find(v => v.name === 'WorkList') || views.find(v => v.path === '/system/work/index')
        saved = existed ? (existed.fullPath || existed.path) : ''
      }
      // 默认回到"我的维修"页面，而不是维修管理页面
      const target = { path: saved || '/system/my-work/index' }
      if (this.$tab && this.$tab.closeOpenPage) this.$tab.closeOpenPage(target)
      else this.$router.push(target)
    },
    openHistory() {
      // 获取维修履历记录
      this.getRepairHistory()
      this.historyVisible = true
    },
    getRepairHistory() {
      // 调用维修履历API - 按设备查询完整维修履历
      import('@/api/asset/asset').then(assetApi => {
        const assetNo = this.order.assetNo || this.work.assetNo
        if (!assetNo) {
          this.$message.warning('无法获取设备编号，无法查询维修履历')
          return
        }
        assetApi.getAssetRepairHistory({ assetNo }).then(res => {
          const records = res.rows || []
          const list = []

          // 添加维修履历记录
          records.forEach(record => {
            list.push({
              time: record.displayTime || record.createdAt,
              operator: record.assigneeName || record.reporterName || record.operatorName || '维修人员',
              operation: record.stepName || '维修步骤',
              description: record.description || record.faultDescription || '',
              result: record.result || ''
            })
          })

          // 如果没有维修履历，添加基本的创建和更新信息
          if (list.length === 0) {
            if (this.work && this.work.createdAt) {
              list.push({
                time: this.work.createdAt,
                operator: this.assigneeName || '系统',
                operation: '创建维修单',
                description: '维修单创建',
                result: ''
              })
            }
            if (this.work && this.work.updatedAt) {
              list.push({
                time: this.work.updatedAt,
                operator: this.assigneeName || '系统',
                operation: '最近更新',
                description: '维修单信息更新',
                result: ''
              })
            }
          }

          // 按时间倒序排列
          list.sort((a, b) => new Date(b.time) - new Date(a.time))
          this.historyList = list
        }).catch((error) => {
          // 如果API调用失败，使用基本数据
          const list = []
          if (this.work && this.work.createdAt) {
            list.push({
              time: this.work.createdAt,
              operator: this.assigneeName || '系统',
              operation: '创建维修单',
              description: '维修单创建',
              result: ''
            })
          }
          if (this.work && this.work.updatedAt) {
            list.push({
              time: this.work.updatedAt,
              operator: this.assigneeName || '系统',
              operation: '最近更新',
              description: '维修单信息更新',
              result: ''
            })
          }
          this.historyList = list
        })
      }).catch((error) => {
        // 如果导入失败，使用基本数据
        const list = []
        if (this.work && this.work.createdAt) {
          list.push({
            time: this.work.createdAt,
            operator: this.assigneeName || '系统',
            operation: '创建维修单',
            description: '维修单创建',
            result: ''
          })
        }
        if (this.work && this.work.updatedAt) {
          list.push({
            time: this.work.updatedAt,
            operator: this.assigneeName || '系统',
            operation: '最近更新',
            description: '维修单信息更新',
            result: ''
          })
        }
        this.historyList = list
      })
    },
    getOperatorName(operatorId) {
      // 这里可以根据operatorId获取操作人员姓名
      // 暂时返回默认值，后续可以优化
      return this.assigneeName || '维修人员'
    },
    formatTime(time) {
      if (!time) return ''
      return this.parseTime(time, '{y}-{m}-{d} {h}:{i}:{s}')
    },
    getTimelineType(operation) {
      if (operation.includes('完成') || operation.includes('成功')) {
        return 'success'
      } else if (operation.includes('失败') || operation.includes('错误')) {
        return 'danger'
      } else if (operation.includes('进行中') || operation.includes('执行')) {
        return 'primary'
      }
      return 'info'
    },
    getResultName(result) {
      const resultMap = {
        'SUCCESS': '成功',
        'FAILED': '失败',
        'PARTIAL': '部分成功'
      }
      return resultMap[result] || result || ''
    },
    getResultTagType(result) {
      const typeMap = {
        'SUCCESS': 'success',
        'FAILED': 'danger',
        'PARTIAL': 'warning'
      }
      return typeMap[result] || 'info'
    },
    statusName(code) {
      const map = {
        PENDING_ASSIGN: '待指派',
        PENDING_EXEC: '已指派',
        IN_PROGRESS: '执行中',
        WAITING_MATERIAL: '待料中',
        DONE: '已完成',
        CONFIRMED: '已确认',
        REJECTED: '拒绝确认'
      }
      return map[code] || code || ''
    },
    typeName(code) {
      const m = {
        EQ_TYPE_001: '数控机床',
        EQ_TYPE_002: '注塑机',
        EQ_TYPE_003: '空压机',
        EQ_TYPE_004: '冷却塔',
        EQ_TYPE_005: '输送带'
      }
      return m[code] || code || ''
    }
  }
}
</script>

<style scoped>
.app-container {
  /* 保持加载遮罩定位稳定，避免内容挂载前高度过小导致位置跳动 */
  min-height: calc(100vh - 180px); /* 根据视口动态计算，确保遮罩始终居中 */
  position: relative;
}
.responsive-table .el-table__body-wrapper { overflow-x: auto; }
.responsive-table .cell { white-space: nowrap; }
.responsive-table .el-table__header-wrapper table,
.responsive-table .el-table__body-wrapper table {
  table-layout: auto !important; /* 让列根据内容与剩余空间自适应 */
  width: 100%;
}
.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}
.detail-header .title {
  font-size: 18px;
  font-weight: 600;
}
.page-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
.mt12 { margin-top: 12px; }

/* 固定右下角返回按钮，避免窗口缩放导致布局混乱 */
.floating-back {
  position: fixed;
  right: 24px;
  bottom: 24px;
  z-index: 10;
}

/* 维修履历弹窗样式 */
.no-history {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.no-history i {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.no-history p {
  margin: 0;
  font-size: 14px;
}

.el-timeline-item .el-card {
  margin-bottom: 0;
}

.el-timeline-item .el-card h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.el-timeline-item .el-card p {
  margin: 4px 0;
  font-size: 13px;
  color: #606266;
}

.el-timeline-item .el-card p strong {
  color: #303133;
}
</style>
